package com.medical.blood.controller;

import com.medical.blood.entity.BloodCollection;
import com.medical.blood.service.BloodCollectionService;
import com.medical.blood.service.SampleStatusService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/sample")
public class SampleController {

    @Autowired
    private BloodCollectionService collectionService;
    @Autowired
    private SampleStatusService statusService;

    /**
     * 接收设备上传的采血记录并初始化样本状态
     * （设备完成采血后调用此接口）
     */
    @PostMapping("/collect")
    public Map<String, Object> saveCollection(@RequestBody BloodCollection collection) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 1. 保存采血记录
            collectionService.saveCollection(collection);
            // 2. 初始化样本状态为“待分离”
            statusService.initSampleStatus(collection.getSampleId());
            result.put("success", true);
            result.put("message", "采血记录已保存，样本状态初始化成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 更新样本状态（如医护人员操作后调用）
     */
    @PostMapping("/updateStatus")
    public Map<String, Object> updateSampleStatus(
            @RequestParam Long sampleId,
            @RequestParam String newStatus,
            @RequestParam(required = false) Date separationTime,
            @RequestParam(required = false) String storageLocation) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = statusService.updateStatus(sampleId, newStatus, separationTime, storageLocation);
            result.put("success", success);
            result.put("message", success ? "状态更新成功" : "样本ID不存在");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 查看样本详情（含采血记录+状态）
     */
    @GetMapping("/detail")
    public Map<String, Object> getSampleDetail(@RequestParam Long sampleId) {
        Map<String, Object> detail = new HashMap<>();
        detail.put("collection", collectionService.getBySampleId(sampleId));
        detail.put("status", statusService.getSampleStatus(sampleId));
        return detail;
    }
}